package com.polaris.live.ui.main.fragment

import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.viewpager2.widget.ViewPager2
import com.blankj.utilcode.util.StringUtils
import com.polaris.live.common.adapter.ViewPagerAdapter
import com.polaris.live.common.cacha.DisplayUtil
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.base2.BaseVbFragment
import com.polaris.live.common.network.parseState
import com.polaris.live.common.util.NavigationBarUtils
import com.polaris.live.databinding.FragmentHotBinding
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.translation.R
import com.polaris.live.translation.R.string
import com.polaris.live.ui.backpack.fragment.ShoppingMallFragment
import com.polaris.live.utils.interfaces.OnAutoRefreshListener
import com.polaris.live.utils.interfaces.OnGotoListener
import com.polaris.live.utils.interfaces.OnRefreshStateListener
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.home.HotViewModel
import com.polaris.live.widget.tab.OnTabSelectListener
import com.polaris.live.widget.tab.TabBean

/**
 * 热门
 *
 * @author Created by lucas on 2023/10/16 13:26
 * @since 1.0.0
 */
class HotFragment : BaseVbFragment<HotViewModel, FragmentHotBinding>(), OnAutoRefreshListener,
    OnGotoListener, OnRefreshStateListener {

    private val mFragments = ArrayList<Fragment>(4)

    private var mIsShowRed = false

    private lateinit var mTabAdapter: ViewPagerAdapter

    override fun initView(savedInstanceState: Bundle?) {
        updateImmersionBar()

        initTitle()
    }

    private fun initTitle() {
        val page = DisplayUtil.getSecondaryPagesByPrimaryPage(DisplayUtil.COMMUNITY)
        val titles = mutableListOf<TabBean>()
        page?.secondaryPages?.forEach {
            when (it) {
                DisplayUtil.COMMUNITY_RECOMMEND -> {
                    titles.add(TabBean(StringUtils.getString(string.recommend)))
                    mFragments.add(CommunityRecommendFragment())
                }

                DisplayUtil.COMMUNITY_NEWCOMER -> {
                    titles.add(TabBean(StringUtils.getString(string.newcomer)))
                    mFragments.add(HotManNewcomerFragment())
                }

                DisplayUtil.COMMUNITY_COMMUNITY -> {
                    titles.add(TabBean(StringUtils.getString(R.string.community_dynamic)))
                    mFragments.add(DynamicFragment())
                }

                DisplayUtil.COMMUNITY_STORE -> {
                    titles.add(TabBean(StringUtils.getString(R.string.shopping_mall)))
                    mFragments.add(ShoppingMallFragment().apply {
                        arguments = bundleOf("isNeedBottom" to true, "isHome" to true)
                    })
                }
            }
        }


        mBinding.tab.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                mBinding.pager.currentItem = position
            }

            override fun onTabReselect(position: Int) {
                onAutoRefresh()
            }
        })

        mBinding.pager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                mFragments.forEachIndexed { index, fragment ->
                    val hidden = index != position
                    if (fragment is ShoppingMallFragment) {
                        fragment.setHomeNeedShow(!hidden)
                        if (hidden) {
                            mBinding.ivGoBack.visibility = View.GONE
                            mBinding.backpackRed.visibility = View.GONE
                        } else {
                            mBinding.ivGoBack.visibility = View.VISIBLE
                            mBinding.backpackRed.visibility = if (mIsShowRed) View.VISIBLE else View.GONE
                        }
                    }
                    fragment.onHiddenChanged(hidden)
                }
            }
        })

        mTabAdapter = ViewPagerAdapter(mFragments, this)
        mBinding.pager.adapter = mTabAdapter
        mBinding.pager.offscreenPageLimit = mFragments.size
        mBinding.tab.setViewPage(mBinding.pager)
        mBinding.tab.setTabs(titles, mBinding.svScroll)

        DisplayUtil.getDefaultIndexBySecondaryPrimaryId(getGotoDate()?.index, DisplayUtil.COMMUNITY, page)?.also {
            mBinding.tab.onPageSelected(it)
            mBinding.pager.setCurrentItem(it, false)
        }

        mBinding.ivGoBack.setOnSingleClickListener {
            GlobalPopupManager.showCompletePopup(requireContext(), isOk = {
                Router.instance.setPath(RoutePath.BACKPACK_ACTIVITY)
                    .withInt("index", 0)
                    .navigation(requireActivity())
            })
        }

        //获取背包红点
        mViewModel.mBackpackNewLiveData.observe(this) { resultState ->
            parseState(resultState, {
                mIsShowRed = it
                if (mBinding.ivGoBack.isVisible) {
                    mBinding.backpackRed.visibility = if (it) View.VISIBLE else View.GONE
                } else {
                    mBinding.backpackRed.visibility = View.GONE
                }
            })
        }
    }

    override fun onAutoRefresh() {
        if (!isCreated()) {
            return
        }

        val fragment = mFragments[mBinding.pager.currentItem]
        if (fragment is OnAutoRefreshListener) {
            (fragment as OnAutoRefreshListener).onAutoRefresh()
        }
    }

    override fun onRefreshState() {
        if (isCreated()) {
            val fragment = mFragments.getOrNull(mBinding.pager.currentItem) ?: return
            if (fragment is OnRefreshStateListener) {
                fragment.onRefreshState()
            }

        }
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)

        if (!hidden) {
            updateImmersionBar()
            mViewModel.getBackpackNew()
        }
        if (isCreated()) {
            val fragment = mFragments.getOrNull(mBinding.pager.currentItem) ?: return
            if (fragment !is ShoppingMallFragment) {
                fragment.onHiddenChanged(hidden)
            }
        }
    }

    override fun onResume() {
        super.onResume()
        mViewModel.getBackpackNew()
    }

    private fun updateImmersionBar() {
        NavigationBarUtils.setImmersionBarForMain(this, mBinding.llTab)
    }

    private var mGotoData: OnGotoListener.GotoData? = null
    override fun onGoto(gotoData: OnGotoListener.GotoData) {
        if (!isCreated()) {
            mGotoData = gotoData
        } else {
            mBinding.pager.currentItem = gotoData.index
        }
    }

    private fun getGotoDate(): OnGotoListener.GotoData? {
        return if (mGotoData == null) {
            null
        } else {
            mGotoData.apply {
                mGotoData = null
            }
        }
    }

}